package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import com.atguigu.spzx.manager.service.CodeImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * title:
 * author: zgl
 * date: 2023/12/26
 * description：
 */
@Service
public class CodeImgServiceImpl implements CodeImgService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Map getCodeImg() {
        //生成验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 50, 4, 20);
        //获取验证码的数值
        String code = circleCaptcha.getCode();

        //缓存验证码数据到redis
        String key = IdUtil.createSnowflake(1, 1).nextIdStr();
        redisTemplate.opsForValue().set("sys:user:code:" + key, code, 5, TimeUnit.MINUTES);

        //向前端返回数据
        String codeImg = circleCaptcha.getImageBase64();
        Map map = new HashMap();
        map.put("codeKey", key);
        map.put("codeImg", "data:image/png;base64," + codeImg);
        return map;
    }
}
